package bjut.zrpc.core.optimization.compress;



import bjut.zrpc.core.optimization.interfaces.Compress;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/24 13:12
 */
public class GzipCompress implements Compress {

    private static final int BUFFER_SIZE = 10 * 1024;

    @Override
    public byte[] compress(byte[] bytes) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
            gzipOutputStream.write(bytes);
            gzipOutputStream.flush();
            gzipOutputStream.close();
            gzipOutputStream.finish();
            return byteArrayOutputStream.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public byte[] deCompress(byte[] bytes) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len;
            while ((len = gzipInputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            return byteArrayOutputStream.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }
}
